package com.controller;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.base.Myprops;
import com.model.auto.Major;
import com.model.auto.School;
import com.model.auto.StuScheme;
import com.model.auto.Student;
import com.model.auto.vo.UptStuSchemeVo;
import com.service.IMajorService;
import com.service.ISchoolService;
import com.service.IStuSchemeService;
import com.service.IStudentService;
import com.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2022-09-14
 */
@RestController
@RequestMapping("/stuScheme")
@Slf4j
public class StuSchemeController{
    @Autowired
    private IStuSchemeService stuSchemeService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private ISchoolService schoolService;
    @Autowired
    private IMajorService majorService;
    @Autowired
    private Myprops myprops;

    //查询方案
    @PostMapping("/getProgramme")
    public R getProgramme(String stuId) {
        Student student = studentService.getById(stuId);

        List<StuScheme> list = stuSchemeService.getProgrammes(stuId);
        String[] regulation = {"提前批A段","提前批B段","提前批C段","提前批专科","国家专项","地方专项","本科一批","一批特殊","本科二批","二批特殊","高职专科"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<StuScheme>() {
            @Override
            public int compare(StuScheme o1, StuScheme o2) {
                String websiteName1 = (String) o1.getBatch();
                String websiteName2 = (String) o2.getBatch();
                int io1 = regulationOrder.indexOf(websiteName1);
                int io2 = regulationOrder.indexOf(websiteName2);
                return (io1 == -1 || io2 == -1) ? (io2 - io1) : (io1 - io2);
            }
        });
        R r = R.ok(list);
        if(Objects.nonNull(student)){
            r.put("score", student.getScore());
            r.put("precedence", student.getPrecedence());
        }else{
            r.put("score", "");
            r.put("precedence", "");
        }
        return r;
    }

    @PostMapping("/getScheme")
    public R getScheme(String stuId, Integer programmeId,String batch) {
        System.out.println("--------=======" + stuId);
        System.out.println("--------方案id" + programmeId);
        List<StuScheme> list = stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
                .eq(!StringUtil.isEmpty(stuId), StuScheme::getStuId, stuId)
                .eq(programmeId != null, StuScheme::getProgrammeId, programmeId)
                .eq(batch != null, StuScheme::getBatch, batch)
        );
        //方案院校排序
        sortScheme(list);


        Boolean isProbability = false;
        Integer precedence = null;
        //如果stuId不为null，计算录取概率
        if(Objects.nonNull(stuId)){
            Student student = studentService.getById(stuId);
            if(Objects.nonNull(student) && !StringUtil.isEmpty(student.getPrecedence()) && StringUtil.isNumeric(student.getPrecedence())){
                isProbability = true;
                precedence = Integer.valueOf(student.getPrecedence());
            }
        }

        //方案专业排序
        sortMajor(list);

        for(StuScheme stuScheme:list){
            if("0".equals(stuScheme.getSchemeChange())){
                stuScheme.setSchemeChangeFlag(true);
            }else{
                stuScheme.setSchemeChangeFlag(false);
            }
            int type = 1;
            if(stuScheme.getMajorType() == 2 || stuScheme.getMajorType() == 4){
                type = 2;
            }
            School school = schoolService.selectOneByParams(stuScheme.getSchoolCode(), type, stuScheme.getBatch(), stuScheme.getRecruitType());
            if(Objects.nonNull(school)){
                stuScheme.setSchoolExamLimit(school.getExamLimit());
                if(isProbability){
                    getSchoolProbability(school, precedence, school.getBatch());
                }
                stuScheme.setProbability(school.getProbability());
                stuScheme.setProbabilityName(school.getProbabilityName());
                stuScheme.setRecruitType(school.getRecruitType());
            }
            //获取专业报考限制
            if(StringUtils.hasText(stuScheme.getMajorList())){
                List<JSONObject> newMajorList = new ArrayList<>();
                List<JSONObject> majorList = JSONArray.parseArray(stuScheme.getMajorList(), JSONObject.class);

                for(JSONObject major:majorList){
                    Major major1 = majorService.selectByParams(type, stuScheme.getSchoolCode(), major.getString("uniqueCode"), stuScheme.getRecruitType());
                    if(Objects.nonNull(major1)){
                        if(isProbability){
                            getMajorProbability(major1, precedence, school.getBatch());
                        }
                        major.put("majorName",major1.getMajorName());
                        major.put("majorCode",major1.getMajorCode());
                        major.put("probability", major1.getProbability());
                        major.put("probabilityName", major1.getProbabilityName());
                        major.put("examLimit", major1.getExamLimit());
                        newMajorList.add(major);
                    }
                }
                stuScheme.setMajorList(JSONObject.toJSONString(newMajorList));
            }
        }
        System.out.println("===========结果" + list);
        return R.ok(list);
    }


    private Integer getCompareSchemeName(String schemeName1, String schemeName2) {
        try {
            Integer num1 = 1;
            Integer num2 = 1;
            String regex = "\\d+"; // 匹配连续的数字
            Pattern pattern = Pattern.compile(regex);
            if("备选".equals(schemeName1)){
                num1 = 99;
            }else{
                Matcher matcher1 = pattern.matcher(schemeName1);
                while (matcher1.find()) {
                    num1 = Integer.valueOf(matcher1.group());
                    break;
                }
            }

            if("备选".equals(schemeName2)){
                num2 = 99;
            }else{
                Matcher matcher2 = pattern.matcher(schemeName2);
                while (matcher2.find()) {
                    num2 = Integer.valueOf(matcher2.group());
                    break;
                }
            }
            return num1.compareTo(num2);
        }catch (Exception e){
            log.error("获取院校排序异常，异常信息=", e);
        }
        return 1;
    }


    @GetMapping("/getSchemePdf")
    public void getSchemePdf(String stuId, Integer programmeId, String batch, HttpServletResponse response) {
        List<StuScheme> list = stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
                .eq(!StringUtil.isEmpty(stuId), StuScheme::getStuId, stuId)
                .eq(programmeId != null, StuScheme::getProgrammeId, programmeId)
                .eq(batch != null, StuScheme::getBatch, batch)
        );

        //方案院校排序
        sortScheme(list);
        //方案专业排序
        sortMajor(list);

        List<List<StuScheme>> scheme = new ArrayList<>();
        scheme.add(list);

        Student student = studentService.getById(stuId);
        String filePath = myprops.getSavePath() + File.separator + DateUtils.format(new Date(), "yyyyMMdd");
        File folder = new File(filePath);
        if (!folder.exists()) {
            folder.mkdirs();
            log.debug("创建文件夹{}成功", filePath);
        }

        String fileName = student.getName() + list.get(0).getProgrammeName()+".pdf";
        PdfUtil.createPdf(filePath + File.separator + fileName, scheme, student, false);


        String downloadFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");

        InputStream input = null;
        OutputStream output = null;
        try{
            File file = new File(filePath + File.separator + fileName);
            input = new FileInputStream(file);
            output = response.getOutputStream();
            byte[] buff = new byte[1024];
            int index;
            while ((index = input.read(buff)) != -1) {
                output.write(buff, 0, index);
                output.flush();
            }
        }catch (Exception e){
            log.error("download template error", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error("关闭input异常：", e);
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    log.error("关闭output异常：", e);
                }
            }
        }
    }

    //删除志愿
    @PostMapping("/deleteScheme")
    public R deleteScheme(Integer Id) {
        System.out.println("=========id是" + Id);
        return R.ok(stuSchemeService.removeById(Id));
    }

    //删除方案
    @GetMapping("/deleteProgramme")
    public R deleteNewStuScheme(Integer programmeId,Integer stuId,String batch){
        if (programmeId!=null&&stuId!=null){
            List<StuScheme> list=stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
                    .eq(StuScheme::getStuId,stuId)
                    .eq(StuScheme::getProgrammeId,programmeId)
                    .eq(StuScheme::getBatch,batch)
            );
            List<Object> idList=new ArrayList<>();
            if (list.size()>0){
                list.forEach(i->{
                    idList.add(i.getId());
                });
            }
            boolean result=stuSchemeService.removeBatchByIds(idList);
            System.out.println("结果"+result);
            if (result){
                return R.ok();
            }
        }
        return R.error();
    }

    //修改方案名称
    @PostMapping("/updateName")
    public R updateName(String name, Integer programmeId, String stuId) {
        stuSchemeService.update(new LambdaUpdateWrapper<StuScheme>()
                .eq(programmeId != null, StuScheme::getProgrammeId, programmeId)
                .eq(!StringUtil.isEmpty(stuId), StuScheme::getStuId, stuId)
                .set(!StringUtil.isEmpty(name), StuScheme::getProgrammeName, name)
        );
        return R.ok();
    }

    //修改方案信息
    @PostMapping("/updateProgramme")
    public R updateProgramme(@RequestBody UptStuSchemeVo uptStuSchemeVo) {
        boolean update = stuSchemeService.update(new LambdaUpdateWrapper<StuScheme>()
                .eq(!StringUtil.isEmpty(uptStuSchemeVo.getStuId()), StuScheme::getStuId, uptStuSchemeVo.getStuId())
                .eq(uptStuSchemeVo.getProgrammeId() != null, StuScheme::getProgrammeId, uptStuSchemeVo.getProgrammeId())
                .set(!StringUtil.isEmpty(uptStuSchemeVo.getBatch()), StuScheme::getBatch, uptStuSchemeVo.getBatch())
                .set(uptStuSchemeVo.getRanking() != null, StuScheme::getRanking, uptStuSchemeVo.getRanking())
                .set(!StringUtil.isEmpty(uptStuSchemeVo.getFraction()), StuScheme::getFraction, uptStuSchemeVo.getFraction())
                .set(StuScheme::getMinfraction, uptStuSchemeVo.getMinfraction())
                .set(StuScheme::getMaxfraction, uptStuSchemeVo.getMaxfraction())
                .set(!StringUtil.isEmpty(uptStuSchemeVo.getProgrammeName()), StuScheme::getProgrammeName, uptStuSchemeVo.getProgrammeName())
                .set(StuScheme::getMaxranking, uptStuSchemeVo.getMaxranking())
                .set(StuScheme::getMinranking, uptStuSchemeVo.getMinranking())
        );
        if (update) {
            return R.ok();
        } else {
            return R.error("修改失败！");
        }
    }

    @PostMapping("/saveScheme")
    public R saveScheme(@RequestBody StuScheme[] stuScheme) {
        Integer maxProgrammeId = stuSchemeService.getObj(new QueryWrapper<StuScheme>()
                .select("ifnull(max(programme_id),0) as maxNum")
                .eq("stu_id", stuScheme[0].getStuId())
                .eq("batch", stuScheme[0].getBatch())
                .orderByDesc("programme_id"), i -> Integer.valueOf(i.toString())
        );
        //默认招生类别
        List<String> defaultRecruitType = new ArrayList<>();
        defaultRecruitType.add("普通志愿");
        defaultRecruitType.add("中外合办");

        List<StuScheme> stuSchemes = Arrays.asList(stuScheme);
        if (stuScheme.length<2&&StringUtil.isEmpty(stuSchemes.get(0).getSchemeName())){
            for (StuScheme scheme : stuScheme) {
                if (scheme.getProgrammeId()==null){

                    stuSchemes.forEach(i->{
                        List<StuScheme> schemes=stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
                                .eq(scheme.getStuId()!=null,StuScheme::getStuId,scheme.getStuId())
                                .orderByDesc(StuScheme::getNum).last("limit 1")
                        );
                        i.setProgrammeId(maxProgrammeId + 1);
                        if(schemes.size()>0){
                            i.setNum(schemes.get(0).getNum()+1);
                        }else {
                            i.setNum(1);
                        }
                    });

                }
                if (StringUtil.isEmpty(scheme.getSchemeName())){
                    Integer count = stuSchemeService.queryGroupByParam(scheme);
                    String majorType="理工";
                    if (scheme.getMajorType()==2 || scheme.getMajorType()==4){
                        majorType="文史";
                    }
                    String name=majorType+scheme.getBatch()+(count+1);
                    stuSchemes.forEach(i->{
                        i.setProgrammeName(name);
                        i.setSelectRecruitType(String.join(",", defaultRecruitType));
                    });
                }
                long count = stuSchemeService.count(new LambdaQueryWrapper<StuScheme>().
                        eq(StuScheme::getProgrammeName, scheme.getProgrammeName())
                        .eq(StuScheme::getStuId, scheme.getStuId())
                        .eq(StuScheme::getBatch,scheme.getBatch())
                );
//                    System.out.println("他的数量" + count);
                if (count > 0) {
                    return R.error("该方案名称已存在！");
                } else {
                    boolean b = stuSchemeService.saveBatch(stuSchemes);
                    //更新序号
                    UpdateSort(stuSchemes.get(0));

                    HashMap<String, Object> object = new HashMap<>();
                    object.put("bol", b);
                    object.put("list", stuSchemes);
                    return R.ok(object);
                }
            }

        }else {
            int programmeid = maxProgrammeId+1;
            if(stuSchemes.get(0).getProgrammeId() != null){
                programmeid=stuSchemes.get(0).getProgrammeId();
            }
            String stuId=stuSchemes.get(0).getStuId();
            if (!StringUtil.isEmpty(stuId)){
                stuSchemeService.remove(new LambdaQueryWrapper<StuScheme>()
                        .eq(StuScheme::getProgrammeId, programmeid)
                        .eq(StuScheme::getStuId,stuId)
                        .eq(StuScheme::getBatch,stuSchemes.get(0).getBatch())
                );
                stuSchemes.removeIf(scheme -> StringUtil.isEmpty(scheme.getSchemeName()));
                stuSchemes.forEach(scheme -> {
                    scheme.setId(null);
                    if(StringUtils.hasText(scheme.getRecruitType()) && !defaultRecruitType.contains(scheme.getRecruitType())){
                        defaultRecruitType.add(scheme.getRecruitType());
                    }
                });
                stuSchemes.forEach(stuScheme1 -> {
                    stuScheme1.setSelectRecruitType(String.join(",", defaultRecruitType));
                });
                boolean b = stuSchemeService.saveOrUpdateBatch(stuSchemes);
                HashMap<String, Object> object = new HashMap<>();
                object.put("bol", b);
                object.put("list", stuSchemes);

                //更新序号
                UpdateSort(stuSchemes.get(0));

                return R.ok(object);
            }else {
                return R.error("保存失败！");
            }



        }



//        for (StuScheme scheme : stuScheme) {
//            System.out.println("========id" + scheme.getProgrammeId());
//            if (scheme.getProgrammeId() == null) {
//                Integer maxProgrammeId = stuSchemeService.getObj(new QueryWrapper<StuScheme>()
//                        .select("ifnull(max(programme_id),0) as maxNum")
//                        .eq("stu_id", stuScheme[0].getStuId())
//                        .orderByDesc("programme_id"), i -> Integer.valueOf(i.toString())
//                );
//                List<StuScheme> schemes=stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
//                        .eq(scheme.getStuId()!=null,StuScheme::getStuId,scheme.getStuId())
//                        .orderByDesc(StuScheme::getNum).last("limit 1")
//                );
//                List<StuScheme> stuSchemes = Arrays.asList(stuScheme);
//                stuSchemes.forEach(i->{
//                    i.setProgrammeId(maxProgrammeId + 1);
//                    if(schemes.size()>0){
//                        i.setNum(schemes.get(0).getNum()+1);
//                    }else {
//                        i.setNum(1);
//                    }
//                });
//                long count = stuSchemeService.count(new LambdaQueryWrapper<StuScheme>().
//                        eq(StuScheme::getProgrammeName, scheme.getProgrammeName())
//                        .eq(StuScheme::getStuId, scheme.getStuId())
//                );
//                System.out.println("他的数量" + count);
//                if (count > 0) {
//                    return R.error("该方案名称已存在！");
//                } else {
//                    boolean b = stuSchemeService.saveBatch(stuSchemes);
//                    HashMap<String, Object> object = new HashMap<>();
//                    object.put("bol", b);
//                    object.put("list", stuSchemes);
//                    return R.ok(object);
//                }
//            } else {
////                stuSchemeService.remove(new LambdaQueryWrapper<StuScheme>()
////                        .eq(scheme.getProgrammeId() != null, StuScheme::getProgrammeId, scheme.getProgrammeId()));
//                List<StuScheme> stuSchemes = Arrays.asList(stuScheme);
//                System.out.println("stuSchemes" + stuSchemes);
//                boolean b = stuSchemeService.saveOrUpdateBatch(stuSchemes);
//                HashMap<String, Object> object = new HashMap<>();
//                object.put("bol", b);
//                object.put("list", stuSchemes);
//                return R.ok(object);
//            }
//        }
        return R.ok();
    }

    @PostMapping("/getPrintScheme")
    public R getPrintScheme(String stuId) {

        List<Object> scheme = new ArrayList<Object>();
        List<StuScheme> list = stuSchemeService.getProgrammes(stuId);

        String[] regulation = {"提前批A段","提前批B段","提前批C段","提前批专科","国家专项","地方专项","本科一批","一批特殊","本科二批","二批特殊","高职专科"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<StuScheme>() {
            @Override
            public int compare(StuScheme o1, StuScheme o2) {
                String websiteName1 = (String) o1.getBatch();
                String websiteName2 = (String) o2.getBatch();
                int io1 = regulationOrder.indexOf(websiteName1);
                int io2 = regulationOrder.indexOf(websiteName2);
                return (io1 == -1 || io2 == -1) ? (io2 - io1) : (io1 - io2);
            }
        });
        List<Integer> codeList = new ArrayList<Integer>();
        List<String> batchList = new ArrayList<String>();
        if (list.size() > 0) {
            list.forEach(i -> codeList.add(i.getProgrammeId()));
            list.forEach(i -> batchList.add(i.getBatch()));
        }
        System.out.println("这个是集合"+list);
        for (int i = 0; i < codeList.size(); i++) {
            List<StuScheme> lists = stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
                    .eq(!StringUtil.isEmpty(stuId), StuScheme::getStuId, stuId)
                    .eq(codeList.get(i) != null, StuScheme::getProgrammeId, codeList.get(i))
                    .eq(batchList.get(i) != null, StuScheme::getBatch, batchList.get(i))
            );
            //方案院校排序
            sortScheme(lists);
            //方案专业排序
            sortMajor(lists);

            scheme.add(i, lists);
        }

        return R.ok(scheme);
    }

    @GetMapping("/getPrintSchemePdf")
    public void getPrintSchemePdf(String stuId, HttpServletResponse response) {
        List<List<StuScheme>> scheme = new ArrayList<>();
        List<StuScheme> list = stuSchemeService.getProgrammes(stuId);

        String[] regulation = {"提前批A段","提前批B段","提前批C段","提前批专科","国家专项","地方专项","本科一批","一批特殊","本科二批","二批特殊","高职专科"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<StuScheme>() {
            @Override
            public int compare(StuScheme o1, StuScheme o2) {
                String websiteName1 = (String) o1.getBatch();
                String websiteName2 = (String) o2.getBatch();
                int io1 = regulationOrder.indexOf(websiteName1);
                int io2 = regulationOrder.indexOf(websiteName2);
                return (io1 == -1 || io2 == -1) ? (io2 - io1) : (io1 - io2);
            }
        });
        List<Integer> codeList = new ArrayList<Integer>();
        List<String> batchList = new ArrayList<String>();
        if (list.size() > 0) {
            list.forEach(i -> codeList.add(i.getProgrammeId()));
            list.forEach(i -> batchList.add(i.getBatch()));
        }
        System.out.println("这个是集合"+list);
        for (int i = 0; i < codeList.size(); i++) {
            List<StuScheme> lists = stuSchemeService.list(new LambdaQueryWrapper<StuScheme>()
                    .eq(!StringUtil.isEmpty(stuId), StuScheme::getStuId, stuId)
                    .eq(codeList.get(i) != null, StuScheme::getProgrammeId, codeList.get(i))
                    .eq(batchList.get(i) != null, StuScheme::getBatch, batchList.get(i))
            );
            //方案院校排序
            sortScheme(lists);

            //方案专业排序
            sortMajor(lists);

            scheme.add(i, lists);
        }

        Student student = studentService.getById(stuId);
        String filePath = myprops.getSavePath() + File.separator + DateUtils.format(new Date(), "yyyyMMdd");
        log.info("保存文件地址:{}",filePath);
        File folder = new File(filePath);
        if (!folder.exists()) {
            folder.mkdirs();
            log.info("创建文件夹{}成功", filePath);
        }
        String fileName = student.getName()+ "高考志愿方案.pdf";
        PdfUtil.createPdf(filePath + File.separator + fileName, scheme, student, false);

        String downloadFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");

        InputStream input = null;
        OutputStream output = null;
        try{
            File file = new File(filePath + File.separator + fileName);
            input = new FileInputStream(file);
            output = response.getOutputStream();
            byte[] buff = new byte[1024];
            int index;
            while ((index = input.read(buff)) != -1) {
                output.write(buff, 0, index);
                output.flush();
            }
        }catch (Exception e){
            log.error("download template error", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error("关闭input异常：", e);
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    log.error("关闭output异常：", e);
                }
            }
        }
    }

    //调整排序
    @PostMapping("UpdateSort")
    public R UpdateSort(@RequestBody StuScheme stuSchemeReq) {
        //查询学生方案信息
        List<StuScheme> list = stuSchemeService.getProgrammes(stuSchemeReq.getStuId());

        String[] regulation = {"提前批A段","提前批B段","提前批C段","提前批专科","国家专项","地方专项","本科一批","一批特殊","本科二批","二批特殊","高职专科"};
        final List<String> regulationOrder = Arrays.asList(regulation);

        //按照batch分组
        Map<String, List<StuScheme>> groupByBatch =
                list.stream().collect(Collectors.groupingBy(StuScheme::getBatch));

        int num = 1;
        for(String batchName:regulationOrder){
            if(!ObjectUtils.isEmpty(groupByBatch.get(batchName))){
                int programmeId = 1;
                for (StuScheme stuScheme : groupByBatch.get(batchName)) {
                    StuScheme updateStuScheme = new StuScheme();
                    String majorType = "理工";
                    if (stuScheme.getMajorType() == 2) {
                        majorType = "文史";
                    }
                    String name = majorType + stuScheme.getBatch() + (programmeId);
                    updateStuScheme.setProgrammeName(name);
                    updateStuScheme.setProgrammeId(programmeId);
                    updateStuScheme.setNum(num);
                    LambdaQueryWrapper wrapper = new LambdaQueryWrapper<StuScheme>()
                            .eq(StuScheme::getStuId, stuScheme.getStuId())
                            .eq(StuScheme::getProgrammeId, stuScheme.getProgrammeId())
                            .eq(StuScheme::getBatch, stuScheme.getBatch());
                    stuSchemeService.update(updateStuScheme, wrapper);
                    programmeId++;
                    num++;
                }
            }
        }

        return R.ok();
    }

    /**
     * 获取院校录取概率
     * @param school
     * @param precedence
     */
    private void getSchoolProbability(School school, Integer precedence, String batch) {
        Map<String,String> probabilityMap = ProbabilityUtils.getOldProbability(school.getProposedwc(), precedence, batch);
        if(StringUtils.hasText(probabilityMap.get("probability"))){
            school.setProbability(probabilityMap.get("probability"));
            school.setProbabilityName(probabilityMap.get("probabilityName"));
        }
    }

    /**
     * 获取专业录取概率
     *
     * @param major
     * @param precedence
     */
    private void getMajorProbability(Major major, Integer precedence, String batch) {
        Map<String,String> probabilityMap = ProbabilityUtils.getOldProbability(major.getMajorWeici(), precedence, batch);
        if(StringUtils.hasText(probabilityMap.get("probability"))){
            major.setProbability(probabilityMap.get("probability"));
            major.setProbabilityName(probabilityMap.get("probabilityName"));
        }
    }

    /**
     * 方案院校排序
     * @param list
     */
    private void sortScheme(List<StuScheme> list) {
        //判断是否全是备选
        long count = list.stream().filter(data -> !"备选".equals(data.getSchemeName())).count();

        if(count == 0){
            //如果全是备选，按照学校id排序
            Collections.sort(list, new Comparator<StuScheme>() {
                @Override
                public int compare(StuScheme scheme1, StuScheme scheme2) {
                    if("备选".equals(scheme1.getSchemeName()) && "备选".equals(scheme2.getSchemeName())){
                        int type = 1;
                        if(scheme1.getMajorType() == 2 || scheme1.getMajorType() == 4){
                            type = 2;
                        }
                        List<School> school1 = schoolService.list(new LambdaQueryWrapper<School>()
                                .eq(School::getCode, scheme1.getSchoolCode())
                                .eq(School::getRecruitType, scheme1.getRecruitType())
                                .eq(School::getType, type)
                                .eq(School::getBatch, scheme1.getBatch())
                        );
                        List<School> school2 = schoolService.list(new LambdaQueryWrapper<School>()
                                .eq(School::getCode, scheme2.getSchoolCode())
                                .eq(School::getRecruitType, scheme2.getRecruitType())
                                .eq(School::getType, type)
                                .eq(School::getBatch, scheme2.getBatch())
                        );
                        if(!ObjectUtils.isEmpty(school1) && !ObjectUtils.isEmpty(school2)){
                            if(school2.get(0).getProposedwc()>school1.get(0).getProposedwc()){
                                return -1;
                            }
                        }
                        return 1;
                    }else{
                        return 1;
                    }
                }
            });
        }else{
            //按照序列名称排序
            Collections.sort(list, new Comparator<StuScheme>() {
                @Override
                public int compare(StuScheme scheme1, StuScheme scheme2) {
                    if(ObjectUtils.isEmpty(scheme1.getSchemeName()) || ObjectUtils.isEmpty(scheme2.getSchemeName())){
                        return 1;
                    }
                    if(scheme1.getSchemeName().equals(scheme2.getSchemeName())){
                        int type = 1;
                        if(scheme1.getMajorType() == 2 || scheme1.getMajorType() == 4){
                            type = 2;
                        }
                        List<School> school1 = schoolService.list(new LambdaQueryWrapper<School>()
                                .eq(School::getCode, scheme1.getSchoolCode())
                                .eq(School::getRecruitType, scheme1.getRecruitType())
                                .eq(School::getType, type)
                                .eq(School::getBatch, scheme1.getBatch())
                        );
                        List<School> school2 = schoolService.list(new LambdaQueryWrapper<School>()
                                .eq(School::getCode, scheme2.getSchoolCode())
                                .eq(School::getRecruitType, scheme2.getRecruitType())
                                .eq(School::getType, type)
                                .eq(School::getBatch, scheme2.getBatch())
                        );
                        if(!ObjectUtils.isEmpty(school1) && !ObjectUtils.isEmpty(school2)){
                            if(school2.get(0).getProposedwc()>school1.get(0).getProposedwc()){
                                return -1;
                            }
                        }
                        return 1;
                    }
                    return getCompareSchemeName(scheme1.getSchemeName(), scheme2.getSchemeName());
                }
            });
        }
    }

    /**
     * 方案专业排序
     * @param lists
     */
    private void sortMajor(List<StuScheme> lists) {
        for(StuScheme stuScheme:lists){
            //获取专业报考限制
            if(StringUtils.hasText(stuScheme.getMajorList())){
                List<JSONObject> majorList = JSONArray.parseArray(stuScheme.getMajorList(), JSONObject.class);
                //专业排序
                Collections.sort(majorList, new Comparator<JSONObject>() {
                    @Override
                    public int compare(JSONObject o1, JSONObject o2) {
                        return getCompareSchemeName(o1.getString("sort"), o2.getString("sort"));
                    }
                });
                stuScheme.setMajorList(JSONObject.toJSONString(majorList));
            }
        }
    }
}
